/*
 * Copyright (C) 2011 Christopher Probst
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of the 'FoxNet AIO' nor the names of its 
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.foxnet.aio.impl;

import java.nio.channels.AsynchronousChannel;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
import java.util.logging.Logger;

import com.foxnet.aio.Event;
import com.foxnet.aio.EventHandler;
import com.foxnet.aio.EventQueue;

/**
 * @author Christopher Probst
 */
final class QueueWorker implements Runnable {

    private static final Logger logger = Logger.getLogger(QueueWorker.class
	    .getName());

    static final class QueueRunnable<C extends AsynchronousChannel> implements
	    Runnable {

	private static final Logger logger = Logger
		.getLogger(QueueRunnable.class.getName());

	private final EventQueue<C> eventQueue;
	private final Event event;

	public QueueRunnable(EventQueue<C> eventQueue, Event event) {
	    this.eventQueue = eventQueue;
	    this.event = event;
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
	    // Get event handler
	    EventHandler<C> eventHandler = eventQueue.getEventHandler();

	    if (eventHandler != null) {
		try {

		    // Try to handle the event
		    eventHandler.handleEvent(eventQueue, event);
		} catch (Exception e) {
		    logger.warning("Failed to handle event \"" + event
			    + "\". Reason: " + e.getMessage());
		}
	    } else {
		// Fine info...
		logger.fine("The event queue \"" + eventQueue
			+ "\" does not contain an event handler. The "
			+ "event \"" + event + "\" will be discarded.");
	    }
	}
    }

    // Create a new linked blocking queue for handling the events
    final TransferQueue<QueueRunnable<?>> queue =
	    new LinkedTransferQueue<QueueRunnable<?>>();

    /*
     * (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
	// As long as the thread is running
	while (!Thread.interrupted()) {
	    try {
		// Take the next runnable or wait if necessary
		QueueRunnable<?> task = queue.take();

		// Run each task
		task.run();
	    } catch (InterruptedException e) {
		logger.finest("The queue worker \"" + this
			+ "\" has been stopped.");
	    }
	}
    }
}
